import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/PromptAction.dart';
import 'package:flutter_enjoy_plus/utils/ShowPhotoDialog.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key, required this.userInfo});
  final Map<String, dynamic> userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  TextEditingController _textController = TextEditingController();
  @override
  String filename = '';
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.userInfo['nickName'] != null &&
        widget.userInfo['nickName'] != '') {
      _textController.text = widget.userInfo['nickName'];
    }
  }

  bool isSelectPhoto = false;
//头像
  getAvatar() {
    if (widget.userInfo['avatar'] != null && widget.userInfo['avatar'] != '') {
      //判断是否是鸿蒙端
      if ((widget.userInfo['avatar'] as String).startsWith('/data')) {
        return Image.file(
          File(widget.userInfo['avatar']),
          width: 30,
          height: 30,
        );
      }
      return Image.network(
        widget.userInfo['avatar'],
        width: 30,
        height: 30,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 30,
      height: 30,
    );
  }

//保存
  _saveBtn() async {
    if (_textController.text.isEmpty) {
      PromptAction.showError('昵称不能为空');
      return;
    }
    RegExp reg = RegExp(r'^[a-zA-Z0-9_\u4e00-\u9fa5]{1,20}$');
    if (!reg.hasMatch(_textController.text)) {
      PromptAction.showError('只允许中文、字母、数字和下划线，长度在 1 - 20 个字符之间');
    }

    if (isSelectPhoto) {
      if (kIsWeb) {
        //网页端上传头像
        FormData data = FormData.fromMap({
          "file": kIsWeb
              ? MultipartFile.fromBytes(
                  await XFile(widget.userInfo["avatar"]).readAsBytes(), //二进制
                  filename: filename,
                  contentType: DioMediaType("image", 'png'),
                )
              : MultipartFile.fromFileSync(widget.userInfo["avatar"]),
          "type": 'avatar'
        });
        var res = await uploadAPI(data);
        widget.userInfo['avatar'] = res["url"];
        // PromptAction.showInfo(res["url"]);
        // return;
      }
    }
    await updateUserInfoAPI({
      'avatar': widget.userInfo['avatar'],
      'nickName': _textController.text
    });
    eventBus.fire(LogSuccessEvent());
    PromptAction.showSuccess('更新昵称成功');
  }

//选择照片
  void _selectPhoto() async {
    ImagePicker picker = ImagePicker();
    XFile? file = await picker.pickImage(source: ImageSource.gallery); // 从相册选择
    if (file != null) {
      bool isSelectPhoto = true;
      filename = file.name;
      setState(() {
        widget.userInfo["avatar"] = file.path; // blob路径
      });
      Navigator.pop(context);
    }
  }

//点击头像半模态
  // _showBindSheet() {
  //   showModalBottomSheet(
  //       context: context,
  //       builder: (context) {
  //         return Container(
  //           width: double.infinity,
  //           height: 180,
  //           alignment: Alignment.center,
  //           child: Column(
  //             children: [
  //               Container(
  //                 height: 60,
  //                 decoration: const BoxDecoration(
  //                     border: Border(
  //                         bottom: BorderSide(width: 0.5, color: Colors.grey))),
  //                 child: GestureDetector(
  //                   onTap: () {},
  //                   child: const Row(
  //                     mainAxisAlignment: MainAxisAlignment.center,
  //                     children: [
  //                       Icon(Icons.camera_alt),
  //                       SizedBox(
  //                         width: 10,
  //                       ),
  //                       Text(
  //                         '拍照',
  //                         style: TextStyle(fontSize: 20),
  //                       )
  //                     ],
  //                   ),
  //                 ),
  //               ),
  //               Container(
  //                 height: 60,
  //                 decoration: const BoxDecoration(
  //                     border: Border(
  //                         bottom: BorderSide(width: 0.5, color: Colors.grey))),
  //                 child: GestureDetector(
  //                   onTap: () {
  //                     _selectPhoto();
  //                   },
  //                   child: const Row(
  //                     mainAxisAlignment: MainAxisAlignment.center,
  //                     children: [
  //                       Icon(Icons.phone_android),
  //                       SizedBox(
  //                         width: 10,
  //                       ),
  //                       Text(
  //                         '相册',
  //                         style: TextStyle(fontSize: 20),
  //                       )
  //                     ],
  //                   ),
  //                 ),
  //               ),
  //               Container(
  //                 height: 60,
  //                 decoration: const BoxDecoration(
  //                     border: Border(
  //                         bottom: BorderSide(width: 0.5, color: Colors.grey))),
  //                 child: GestureDetector(
  //                   onTap: () {
  //                     Navigator.pop(context);
  //                   },
  //                   child: const Row(
  //                     mainAxisAlignment: MainAxisAlignment.center,
  //                     children: [
  //                       Icon(Icons.cancel_outlined),
  //                       SizedBox(
  //                         width: 10,
  //                       ),
  //                       Text(
  //                         '取消',
  //                         style: TextStyle(fontSize: 20),
  //                       )
  //                     ],
  //                   ),
  //                 ),
  //               ),
  //             ],
  //           ),
  //         );
  //       });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: getAvatar(),
                      ),
                      onTap: () {
                        // _showBindSheet();
                        showBindSheet(context, () {
                          _selectPhoto();
                        });
                      },
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _textController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _saveBtn();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
